package com.ali.service.impl;

import com.ali.service.RedisService;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LettuceServiceImpl implements RedisService {
    private static final RedisURI redisURI;

    static {
        redisURI = RedisURI.builder().withHost("172.29.240.9").withPort(6379).withPassword("hello".toCharArray()).build();
    }

    @Override
    public String set(String key, String value) {
        return redis(key, value);
    }

    @Override
    public String get(String key) {
        return redis(key);
    }

    private String redis(String key, String value) {
        try (RedisClient redisClient = RedisClient.create(redisURI); StatefulRedisConnection<String, String> statefulRedisConnection = redisClient.connect()) {
            RedisCommands<String, String> redisCommands = statefulRedisConnection.sync();
            if (Objects.nonNull(value)) {
                return redisCommands.set(key, value);
            } else {
                return redisCommands.get(key);
            }
        }
    }

    private String redis(String key) {
        return redis(key, null);
    }
}